import { connect } from 'dva';
import { useState, useEffect } from 'react';
import { Row, Col, Icon, Input } from 'antd';
import InfiniteScroll from 'react-infinite-scroller';
import './index.css';
import AxModal from '@/components/AxForm/AxModal';

const { Search } = Input;
/** 切换应用 */
const ChangeApp = props => {
  const [apps, setApps] = useState([]);
  const { handleVisible, dispatch, otherApp } = props;

  useEffect(() => {
    setApps(otherApp);
  }, [props.otherApp]);

  const handleRead = () => {
    const currentApp = JSON.parse(localStorage.getItem('ax-data-app'));
    if (currentApp) {
      return dispatch({
        type: 'user/fetchOtherApp',
        params: {
          currentAppId: currentApp.appId,
          appNumber: 0,
        },
      });
    }
  };

  const gotoApp = obj => {
    if (handleVisible) handleVisible();
    localStorage.removeItem('ax-auth-token');
    location.href = location.origin + '?t=' + obj.appHost;
  };

  const handleSearch = val => {
    const filterApp = otherApp.filter(f => f.appName.indexOf(val) !== -1);
    setApps(filterApp);
  };

  return (
    <AxModal
      title="切换应用"
      footer={null}
      width="40%"
      bodyStyle={{ backgroundColor: 'rgb(89, 89, 89)' }}
      {...props}
      handleRead={handleRead}
      items={[
        <Search placeholder="搜索" onSearch={handleSearch} className="ax-search" allowClear />,
        <div className="ax-infinite-container">
          <InfiniteScroll
            initialLoad={false}
            pageStart={0}
            loadMore={() => {}}
            // hasMore={!this.state.loading && this.state.hasMore}
            useWindow={false}
          >
            <Row gutter={[1, 1]}>
              {apps.map(m => (
                <Col span={6} key={m.appId}>
                  <div className="ax-app" onClick={() => gotoApp(m)}>
                    <div className="ax-app-icon">
                      <img className="ax-app-img" src="/img/1.jpg" />
                    </div>
                    <div className="ax-app-text">{m.appName}</div>
                  </div>
                </Col>
              ))}
            </Row>
          </InfiniteScroll>
        </div>,
      ]}
    />
  );
};

export default connect(({ user, loading }) => ({
  otherApp: user.otherApp,
  loading: loading.models.user,
}))(ChangeApp);
